<template>
  <div class="project-setting project-status-setting">
    <div class="setting-header">
      <div class="setting-title-detail">
        {{ $t('projectManage.setting.authSetting.authTip') }}
      </div>
      <div class="setting-action">
        <el-button type="primary" @click="handleAdd"><i class="el-icon-plus"></i> {{$t('projectManage.setting.authSetting.createBtn')  }}</el-button>
      </div>
    </div>
    <div class="setting-content" v-loading="loading">
      <template>
        <BaseListForNoData v-show="!loading && tableData.length === 0" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
        <!-- 工单备注 table -->
        <div class="table-wrapper" v-if="tableData.length > 0">
          <el-table
          v-table-style
          :data="tableData"
          border
          header-row-class-name="common-list-table-header__v2"
          >
          <el-table-column
            v-for="(column, index) in columns"
            :key="`${column.displayName}_${index}`"
            :prop="column.fieldName"
            :label="column.displayName"
            :min-width="column.minWidth || '108px'"
            show-overflow-tooltip
          >
          <template slot-scope="scope">
            <template v-if="column.fieldName === 'name'">
              {{getRealLabel('name', scope.row)}}
            </template>
            <template v-if="column.fieldName === 'description'">
              {{getRealLabel('description', scope.row)}}
            </template>
          </template>
          </el-table-column>
          <el-table-column fixed="right" :label="$t('common.base.table.col.operator')">
            <template slot-scope="scope">
              <el-button 
                @click="editRow(scope.row)" 
                v-if="scope.row.type !== 1"
                type="text"
              >
              {{$t('common.base.edit')}}
              </el-button>
              <el-button
                type="text"
                size="small"
                class="danger-btn"
                v-if="scope.row.type !== 1"
                @click="deleteRow(scope.row)"
              >
              {{$t('common.base.delete')}}
              </el-button>
            </template>
          </el-table-column>
          </el-table>
        </div>
      </template>
    </div>
    <!-- 新建状态弹窗 -->
    <create-auth ref="CreateAuthModal" :authActionList="authActionList" :dataAuthList="dataAuthList" @submit="submit"></create-auth>
  </div>
</template>
<script>
import NoDataView from '@src/component/common/NoDataViewNew';
import CreateAuth from '@src/modules/setting/projectManage/components/AuthSetting/components/CreateAuth.vue'
import _,{ cloneDeep }  from 'lodash';
import * as ProjectManage from '@src/api/ProjectManage.ts';
import locales from '@src/locales';

export default {
  name: 'auth-setting',
  data() {
    return  {
      tableData: [],
      authActionList: [], // 可以操作的权限
      dataAuthList: [],
      loading: false,
    }
  },
  components: {
    NoDataView,
    CreateAuth
  },
  props: {
    templateId: {
      type: String | Number,
      default: '',
    }
  },
  computed: {
    columns() {
      let columns = [
        {
          displayName: this.$t('common.base.roleName'),
          fieldName: 'name',
          setting: {
            originalFormType: 'text',
          },
        },
        {
          displayName: this.$t('common.base.explain'),
          fieldName: 'description',
          setting: {
            originalFormType: 'text',
          },
          minWidth: '240px',
        },
      ];
      return columns;
    },
  },
  // 页面初始化
  mounted() {
    this.getTableData()
    this.getAuthList()
  },
  methods: {
    getTableData() {
      this.loading = true
      ProjectManage.roleDataList({templateId: this.templateId}).then((res) => {
        this.loading = false
        if (res.success) {
          this.tableData = res.data || []
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getAuthList()  {
      ProjectManage.authList().then((res) => {
        if (res.success)  {
          if (locales.locale != 'zh')
            res.data.forEach((value,item) => {
              res.data[item].name = res.data[item].language[locales.locale].name;
            })
          this.authActionList = res.data || []
          this.dataAuthList = res.data.filter((item) => item.depth === 3)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 添加权限
    handleAdd() {
      this.dataAuthList.forEach((item) => {
        item.depth = 3 // 重置为 全部
      })
      this.$refs.CreateAuthModal.openDialog()
    },

    onMove(e) {
      let index = e.relatedContext.index
      if (index === 0 || index === (this.tableData.length - 1)) {
        return false
      }
      return true
    },

    // 删除权限角色
    deleteRow(item) {
      let params = {
        roleId: item.id,
        templateId: this.templateId, // 项目类型id
      }
      this.$confirm(this.$t('projectManage.setting.deleteTip1'), this.$t('common.base.delete'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
      .then(() => {
         ProjectManage.roleDelete(params).then((res)=> {
          if (res.success) {
            // 更新列表数据
            this.getTableData()
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },

    submit(form, isEdit) {
      if (isEdit) {
        // 初始化选中的 数组id 赋值
        ProjectManage.roleUpdate(form).then((res) => {
          if (res.success) {
            // 刷新页面
            this.$refs.CreateAuthModal.closeDialog()
            this.getTableData()
          } else {
            this.$message.error(res.message)
          }
        })
      } else {
        let params = {
          ...form,
          templateId: this.templateId, // 项目类型id
        }
        ProjectManage.roleAdd(params).then((res)=> {
          if (!res.success) return this.$message.error(res.message)
          this.$message.success(this.$t('common.base.tip.createSuccess2'));
          this.$refs.CreateAuthModal.closeDialog()
          this.getTableData()
        })
      }
    },
    editRow(item) {
      this.dataAuthList.forEach((item) => {
        item.depth = 3 // 重置为 全部
      })
      ProjectManage.roleDetail({roleId: item.id}).then((res) => {
        if (res.success) {
          let detailData = res.data || {}
          this.dataAuthList.forEach((item) => {
            detailData.auths.forEach((ele) => {
              if (item.id === ele.id) {
                item.depth = ele.depth
              }
            })
          })
          this.$refs.CreateAuthModal.openDialog(detailData, true)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getRealLabel(type, data){
      let locale = this.$i18n.locale
      if(data.language?.[locale]){
        return data.language?.[locale]?.[type]
      }
      return data[type]
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@src/modules/setting/projectManage/common/setCommon.scss';
.project-setting {
  .setting-header {
    .setting-title-detail {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #595959;
      line-height: 20px;
    }
  }
}
</style>